package com.arron.juc;

/**
 * @Classname SpinLockDemo
 * @Description TODO
 * @Date 2020/8/21 1:42
 * @Created by 刘
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 *
 * 请手写一个自旋锁
 *  缺点：如果长时间不能获取锁，cpu资源将耗尽，一直在循环
 *
 */

public class SpinLockDemo {

    //使用原子引用线程类
    static AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void mylock(){

        Thread thread = Thread.currentThread();

        //自旋
        do {

        }while (!atomicReference.compareAndSet(null,thread));
        System.out.println(thread.getName()+"\t 获取锁成功。。。。。。。。。。");
    }

    public void myunlock(){

        atomicReference.compareAndSet(Thread.currentThread(),null);
        System.out.println(Thread.currentThread().getName()+"\t 释放锁。。。。。。。。。");
    }


    public static void main(String[] args) {

        SpinLockDemo lockDemo = new SpinLockDemo();

        new Thread(()->{
            lockDemo.mylock();
            try {
                System.out.println(Thread.currentThread().getName()+"执行业务逻辑中。。。。。。。");
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lockDemo.myunlock();
        },"AA").start();


        //主线程睡眠1秒，保证线程A先创建
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(()->{
            lockDemo.mylock();
            try {
                System.out.println(Thread.currentThread().getName()+"执行业务逻辑中。。。。。。。");
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lockDemo.myunlock();
        },"BB").start();

    }

}
